import { Config } from '../../utils/config.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showpost:true,
    qrCode: Config.domain+"/storage/qrcode.jpg", //二维码
    canvasHeight:'0',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var h = (wx.getSystemInfoSync().windowWidth / 2) + 80;
    this.setData({
      canvasHeight: h,
      user:wx.getStorageSync('userInfo'),
    })
    this.getQrcode();
  },
  //下载二维码图片
  getQrcode: function () {
    wx.showLoading({
      title: '正在加载图片',
      mask: true,
    });
    var that = this;
    that.setData({
      showpost: true
    })
    var qrCode = that.data.qrCode;
    if (qrCode) {
      wx.downloadFile({
        url: qrCode,
        success: function (res) {
          if (res.statusCode === 200) {
            var imgSrc = res.tempFilePath;
            that.setData({
              qrCode: imgSrc,
            });
            that.sharePosteCanvas();
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                that.sharePosteCanvas();
              }
            })
          }
        }
      })
    } else {
      that.sharePosteCanvas();
    }
  },
  
  //canvas绘制分享海报
  sharePosteCanvas: function () {
    wx.hideLoading();
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    const ctx = wx.createCanvasContext('myCanvas', that);
    var width = "";
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas-container').boundingClientRect(function (rect) {
      var user = that.data.user;
      var right = rect.right;
      width = rect.width;
      var left = rect.left;
      //画布白色背景
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, width, that.data.canvasHeight);
      //二维码
      if (that.data.qrCode) {
        ctx.drawImage(that.data.qrCode, 20, 20, width - 40, width - 40)
      }
      //文字
      ctx.setFontSize(14);
      ctx.setFillStyle('#000');
      ctx.fillText('赠送人：', 10, width+10);
      ctx.fillText(user.nickName, 70, width+10);
      ctx.fillText('亲，送您一张卡券，请收下吧', 10, width+30);
    }).exec()
    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
      that.setData({
        showShareImg: true
      })
    }, 500)

  },
  textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closePoste();
                  if (res.confirm) {
                  }
                },
                fail: function (res) {
                  console.log(res)
                }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        },
        fail: function (err) {
          console.log(err)
        }
      }, that);
    }, 1000);
  },
  //关闭海报
  closePoste: function () {
    wx.navigateBack()
  },
})